package com.h5lib.nchupfficeApp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.baidu.mobstat.StatService;
import com.baidu.ops.appunion.sdk.AppUnionSDK;
import com.baidu.ops.appunion.sdk.banner.BaiduBanner;
import com.baidu.ops.appunion.sdk.banner.BannerType;
import com.h5lib.nchuoffice.App;

/**
 * 主界面
 * @author farmer
 *
 */
public class MainActivity extends Activity{
	
	@SuppressLint("HandlerLeak")
	private class InitHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				browser.loadUrl(Config.DOMAIN+":"+Config.PORT+Config.WELCOME);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}
	
	/**
	 * 初始化Handler
	 */
	private Handler initHandler = new InitHandler();
	/**
	 * 浏览器
	 */
	private WebView browser;
	/**
	 * 进度条
	 */
	private ProgressBar progressBar;
	
	private Exit exit = new Exit(); 
	
	private RelativeLayout mview = null;
	/**
	 * loadingView
	 */
	private View loadingView=null;
	/**
	 * 
	 */
	private BaiduBanner mBaiduBanner_Image_Text = null;
	
	@SuppressLint({ "InflateParams", "InlinedApi" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		browser = (WebView) findViewById(R.id.browser);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		mview = (RelativeLayout) findViewById(R.id.mview);
		LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		loadingView=inflater.inflate(R.layout.activity_splash, null);
		RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); 
		lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
		lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
		mview.addView(loadingView,lp);
		intiAd();
		initBrowser();
		/**
		 * 设置
		 */
		browser.setWebViewClient(new WebViewClient() {
			/**
			 * 防止链接调用系统浏览器
			 */
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
			/**
			 * 显示推荐应用
			 */
			@Override
			public void onLoadResource(WebView view, String url) {
				if(url.indexOf("doShowAppList") != -1){
					initHandler.post(new Runnable() {
						@Override
						public void run() {
							AppUnionSDK.getInstance(MainActivity.this).showAppList();
						}
					});
				}
				if(url.indexOf("doCheckUpdate") != -1){
					BDAutoUpdateSDK.uiUpdateAction(MainActivity.this, new UICheckUpdateCallback() {
						@SuppressLint("ShowToast")
						@Override
						public void onCheckComplete() {
							Toast.makeText(MainActivity.this, "检测完成！", Toast.LENGTH_SHORT).show();;
						}
					});
				}
				
				super.onLoadResource(view, url);
			}
			/**
			 * 
			 */
			@Override
			public void onPageFinished(WebView view, String url) {
				loadingView.setVisibility(View.GONE);
				if(url.endsWith("home.html")){
					mBaiduBanner_Image_Text.setVisibility(View.VISIBLE);
				}
				else{
					mBaiduBanner_Image_Text.setVisibility(View.GONE);
				}
				super.onPageFinished(view, url);
			}
		});
		/**
		 * 设置提示框
		 */
		browser.setWebChromeClient(new WebChromeClient(){
			@Override  
		    public void onProgressChanged(WebView view, int newProgress) {
		    	progressBar.setVisibility(View.VISIBLE);
		    	progressBar.setProgress(newProgress);
		        if(newProgress==100){
		        	progressBar.setVisibility(View.GONE);
		        }
		    	super.onProgressChanged(view, newProgress);
		    }
		    
		});
		try {
			String db = getApplicationContext().getDatabasePath("nchu_cache.db").getAbsolutePath();
			if(!new File(db).exists()){
				new File(db).getParentFile().mkdirs();
				InputStream dbIn = getClass().getResourceAsStream("/assets/nchu_cache.db");
				IoUtil.copy(dbIn, new FileOutputStream(db));
			}
			App.main(new String[]{""+Config.PORT,db});
			initHandler.sendEmptyMessage(1);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		} 
		
	}

	
	private void intiAd() {
		AppUnionSDK.getInstance(this).initSdk();
		mBaiduBanner_Image_Text = new BaiduBanner(this); 
		mBaiduBanner_Image_Text.setBannerType(BannerType.IMAGE_ONLY);
		RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
		lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
		lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
		mview.addView(mBaiduBanner_Image_Text, lp);
		mBaiduBanner_Image_Text.setVisibility(View.GONE);
		
	}


	@SuppressLint("SetJavaScriptEnabled")
	private void initBrowser() {
	    WebSettings localWebSettings = this.browser.getSettings();
	    localWebSettings.setAllowFileAccess(true);
	    localWebSettings.setJavaScriptEnabled(true);
	    localWebSettings.setDomStorageEnabled(true);
	    localWebSettings.setDatabaseEnabled(true);    
	}
	
	/**
	 * 按返回
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			pressAgainExit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 再按一次退出
	 */
	private void pressAgainExit() {
		if (exit.isExit()) {
			System.exit(-1);
		} else {
			Toast.makeText(getApplicationContext(), "再按一次退出程序",
					Toast.LENGTH_SHORT).show();
			exit.doExitInOneSecond();
		}
	}
	
	@Override
	protected void onResume() {
		StatService.onResume(this);
		super.onResume();
	}

	@Override
	protected void onPause() {
		StatService.onPause(this);
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		AppUnionSDK.getInstance(this).quitSdk();
		super.onDestroy();
	}
}
